<template>

  <view class="postArtice">

    <view class="upNavbar">
      <u-navbar title="发布科普" :safeAreaInsetTop="true" :placeholder="true" autoBack :titleStyle="{
                   'fontSize':'16px',
                   'fontWeight':'600',
                   'color':'#000'
                 }">
        <template #right>
          <view class="u-nav-slot u-flex u-row-center">
            <view @click='saveHTML(1)' v-if="isCanSub" class="colorText">预览</view>
            <view v-else >预览</view>
            <up-line direction="column" :hairline="false" length="16" margin="0 8px"></up-line>
            <view @click='saveHTML(2)' class="colorText1" v-if="isCanSub">发布</view>
            <view   v-else >发布</view>
          </view>
        </template>
      </u-navbar>
    </view>
    <view class="content">
      <view class="trendsTitle">
        <view class="inputBox">
          <textarea placeholder="请输入标题（5~30字)" v-model.trim="articleTitle" placeholder-style="color:#bcbcbc" autofocus
              auto-height :adjust-position="false" :maxlength="30" @input="articleTitleChange" />
        </view>
      </view>
      <view>
        <lsj-edit ref="lsjEdit" placeholder="写些什么和大家分享一下吧~" :maxCount="200" @onReady="editReady" :html="htmlcontent">
          <template #btns>
            <view style="height:228rpx"></view>
            <view :style="`height:${keysHeight}px`" v-if="active === true"></view>
            <view class="fixed-bottom" :class="active === true ? 'on' : ''">
              <view class="u-flex u-row-between postBottom">
                <view class=" u-flex postBottomItem" @click="showCate=true">
                  <image src="https://ossresource.miyingbl.com/def/0385c20240523154216788.png" mode="">
                  </image>
                  <view class="title">选择标签</view>
                  <view v-if="currentCate?.title " class="u-line-1" style="width: 100rpx;">{{ currentCate.title }}
                  </view>
                  <view v-else style="color:#aaa">请选择</view>
                  <image src="https://ossresource.miyingbl.com/uploads/20240416/a16a3c69819db2a7146c7866672b3edb.png"
                    size="16" class="arrowRight"></image>
                </view>
                <view class=" u-flex postBottomItem " @click.stop="navigateTo('/socials/drafts/drafts')">
                  <image src="https://ossresource.miyingbl.com/def/4fab0202405231611432078.png" mode="">
                  </image>
                  <view class="u-flex-1 u-p-l-10">草稿</view>
                  <view>草稿（{{ countDrafts }}）</view>
                  <image src="https://ossresource.miyingbl.com/uploads/20240416/a16a3c69819db2a7146c7866672b3edb.png"
                    size="16" class="arrowRight"></image>
                </view>
              </view>
              <edit-btns :edit="editData" @click="onTabClick"   ref="editBtnsR"></edit-btns>
            </view>
          </template>
        </lsj-edit>
      </view>
    </view>
  </view>
  <u-popup :show="showCate" @close="closeCate" @open="openCate" :round="10" closeable>
    <view class="popupTitle"> <text>选择标签</text> </view>
    <view class="yu-datetime-view">
      <picker-view :indicator-style="itemHeight" :value="dateValues" @change="bindDateChange"
        indicator-class="picker-box">
        <picker-view-column class="yu-picker-column">
          <view class="yu-datetime-item" v-for="(item, index) in cates1" :key="index">{{
            item.title
          }}</view>
        </picker-view-column>
        <picker-view-column class="yu-picker-column1">
          <view class="yu-datetime-item" v-for="(item, index) in cates2" :key="index">{{ item.title }}</view>
        </picker-view-column>
      </picker-view>
    </view>
    <view class="comfirmBtn" @click="comfirmCate">确定</view>
  </u-popup>
  <u-action-sheet
    :actions="sheetList"
    :closeOnClickOverlay="true"
    :closeOnClickAction="true"
    @select="selectClick"
    description="您将退出编辑，是否要保存草稿？"
    :show="showSheet"
    :safeAreaInsetBottom="true"
    cancelText="取消"
    @close="closeSheet"
    round="30"
  ></u-action-sheet>
</template>

<script setup>

import dayjs from 'dayjs'
  import {
    ref,
    nextTick,
    watch
  } from "vue"
  import editBtns from '@/uni_modules/lsj-edit/components/lsj-edit/edit-btns/edit-btns.vue';
  import {
    onLoad,
    onPullDownRefresh,
    onReachBottom,
    onReady,
    onPageScroll,
    onShow,
    onBackPress,
    onUnload
  } from '@dcloudio/uni-app'
import { navigateTo, showToast, navigateBack ,redirectTo} from '@/utils'
  const editData = ref(null)
  const itemHeight = ref(`height: 88rpx`)
  import {
    useMemberStore,
    useSystemStore
  } from '@/stores'
  const System = useSystemStore()
  const userStore = useMemberStore()
  const token = userStore?.token
  const userInfo = ref(userStore.userInfo)
  console.log(System)
  const form = ref({})
  const safeArea = ref(0)
  const currentTab = ref('')
  const keysHeight = ref(0)
  const listenkeysHeight = ref(0)
  import {
    uploadApi
  } from '@/utils/upLoad'
  import {
    coupePostApi,
    kepuCateApi,
    CoupeDraftsApi,
    CoupeDraftsEditApi,
    coupeDetailsApi,
    CoupeDraftsAddApi,
    CoupeDraftsDetailApi
  } from '@/api/social'
  const articleTitle = ref('')
  const editBtnsR = ref(null)
  const showCate = ref(false)
  const showSheet=ref(false)
  const dateValues = ref([1, 1])
  const closeCate = () => {
    showCate.value = false
  }
  const articleTitleChange = (e) => {
    console.log(e)
    getContent()
  }

  const openCate = () => {

  }
  const htmlcontent = ref('')
  const isCanSub = ref(false)
  const countDrafts = ref(0)
  const editsId=ref(null)
  const cates1 = ref([])  //一级分类
  const cates2 = ref([]) //二级分类
  onLoad(async (options) => {

    // 获取科普分类
   let res1=await getCate()
   console.log(res1,11211)

    // #ifdef APP-PLUS || APP-IOS || APP-ANDROID
    uni.onKeyboardHeightChange(res => {
      console.log(res.height)
      if (res.height > 0) {
        keysHeight.value = 0
        // console.log(this.keysHeight)
        listenkeysHeight.value = JSON.parse(JSON.stringify(res.height))
      } else {
        // console.log(this.listenkeysHeight)
        // console.log(this.listenkeysHeight)
        if (currentTab.value) {
          keysHeight.value = listenkeysHeight.value
        } else {
          keysHeight.value = 0
        }
      }
    })
    // #endif

    if(options?.id){
      editsId.value=options?.id
      let result = await coupeDetailsApi({  article_id: options.id,  type:2})
      articleTitle.value = result.data.title
      htmlcontent.value= result.data.content
      imgList.value.push(result.data.image)
      isCanSub.value=true
      currentCate.value=cateArray.value.find(v=>v.id==result.data.category)
      if(currentCate.value.pid!=0){
        let index1=cates1.value.findIndex(v=>v.id==currentCate.value.pid)
        let index2=cates2.value.findIndex(v=>v.id==currentCate.value.id)
        nextTick(()=>{
           dateValues.value = [index1, index2]
        })
      }else{
        let index=cates1.value.findIndex(v=>v.id==currentCate.value.id)
        nextTick(()=>{
             dateValues.value = [index, 0]
        })
      }

      // console.log(cateItem)
    }

    let editDrafts = uni.getStorageSync('editDrafts');
    if(options?.editId){
      let itemRes = await CoupeDraftsDetailApi({  id: options.editId})
      let item=itemRes.data
        flag.value = true
        console.log(item)
        DraftsId.value = item.id

        htmlcontent.value= item?.content
        articleTitle.value = item.title
        htmlcontent.value= item.content
        if (item.link_url.length>0) {
           imgList.value.push(item.link_url)
        }
        isCanSub.value=true
        if (item.tag) {
          currentCate.value=cateArray.value.find(v=>v.id==item.tag)
        }
      }
      let kepuContentPP = uni.getStorageSync('kepuContentPP');
      if(kepuContentPP){
        if(kepuContentPP?.title){
           articleTitle.value = kepuContentPP.title
        }

        htmlcontent.value= kepuContentPP.content
        imgList.value.push(kepuContentPP.images)
        isCanSub.value=true
        if(kepuContentPP?.caogao_id){
         DraftsId.value=kepuContentPP?.caogao_id
        }
        if(kepuContentPP?.id){
            editsId.value=kepuContentPP.id
        }
        nextTick(()=>{
          if(kepuContentPP?.category){
            console.log(cateArray.value)
            currentCate.value=cateArray.value.find(v=>v.id==kepuContentPP.category)
            console.log(currentCate.value)
            if(currentCate.value?.pid!=0){
              let index1=cates1.value.findIndex(v=>v.id==currentCate.value.pid)
              let index2=cates2.value.findIndex(v=>v.id==currentCate.value.id)
              nextTick(()=>{
                 dateValues.value = [index1, index2]
              })
            }else{
              let index=cates1.value.findIndex(v=>v.id==currentCate.value.id)
              nextTick(()=>{
                   dateValues.value = [index, 0]
              })
            }
          }
        })

      }

  })

  const currentCate = ref({})  //已经选择分类
  const cateArray = ref([])  //选择分类
  // 获取分类
  const getCate =async () => {
    let res=await kepuCateApi()
    if(res){
      cates1.value = res.data

      if (cates1.value[0]._child) {
        cates2.value = cates1.value[0]._child
      }
      let arr=res.data
      let array=[]
      for(let i=0;i<arr.length;i++){
        if(arr[i]._child){
          array=array.concat(arr[i]._child)
        }else{
          array=array.concat(arr[i])
        }
      }
     nextTick(_=>{
       dateValues.value = [0, 0]
       cateArray.value=array
       return array;
     })
    }
  }

  const active = ref(false)
  onShow(async () => {
    // 获取草稿箱数量
    let res = await CoupeDraftsApi({
      type: 2
    })
    if (res) {
      countDrafts.value = res.data.total
    }
  })
  onReady(() => {
    // getHeight()
  })
  // 确认分类
  const comfirmCate = () => {
    let value = dateValues.value
    if (cates1.value[value[0]]._child && cates1.value[value[0]]._child.length > 0) {
      let item = cates1.value[value[0]]
      currentCate.value = cates1.value[value[0]]._child[value[1]]
    } else {
      currentCate.value = cates1.value[value[0]]
    }
    closeCate()
    // console.log(currentCate.value)
  }
  // 改变分类
  const bindDateChange = (e) => {
    let value = e.detail.value
    dateValues.value = value
    if (cates1.value[value[0]]._child) {
      cates2.value = cates1.value[value[0]]._child
      nextTick(() => {
        // dateValues.value[1] = 0
      })
    }else{
       cates2.value = []
        dateValues.value[1] = 0
    }
    console.log(dateValues.value)
  }

  const editReady = (edit) => {
    // 将富文本对象存放到当前页面，便于后续直接操作
    editData.value = edit;
    // 	console.log(edit)

    // 	// 演示----监听光标进入
    editData.value.$on('edit:focus', (e) => {
      // console.log('监听光标进入', e);
      editBtnsR.value.removeActive()
      active.value = false
      getContent()
    });
    // 	// 演示----监听输入
    editData.value.$on('edit:input', (e) => {
      // console.log('监听输入', e);
      // htmlcontent.value = e.detail.text
    });
    // 	// 演示----监听光标指向不同样式时回调
    // 	this.edit.$on('edit:statuschange', (e) => {
    // 		// console.log('监听光标当前位置样式变化',JSON.stringify(e));
    // 	})
  }

  const getContent = async () => {
    let imgs = await editData.value.getImages()
    if (editData.value.textCount || imgs.length || articleTitle?.value?.length) {
      isCanSub.value= true
    } else {
      isCanSub.value=  false
    }
    console.log(isCanSub.value)
  }

  const imgList = ref([])
  // 演示----按钮组件点击事件
  const onTabClick = ({
    name,
    index
  }) => {
    console.log(name, index)
    let arr = ['emoji', 'editor', 'paragraph'];
    if (name === currentTab.value) {
      currentTab.value = '';
      active.value = false
    } else if (arr.includes(name)) {
      active.value = true
      currentTab.value = name;
    }

    switch (index) {
      // 插入话题
      case 0:
        addLink();
        break;
        // @某人
      default:
        break;
    }
  }
  async function submit(html) {

    if(!articleTitle.value){
      uni.showToast({
        title: '请输入标题！',
        icon: 'none'
      });
      return false
    }
    if(articleTitle.value.length<5){
      uni.showToast({
        title: '标题最少五个字！',
        icon: 'none'
      });
      return false
    }
    console.log(html)
    if(!currentCate.value?.id){
      uni.showToast({
        title: '请选择标签！',
        icon: 'none'
      });
      return false
    }
    let data={
      title: articleTitle.value,
      content: html,
      images: imgList.value[0],
      category: currentCate.value?.id
    }
    if(DraftsId.value){
      data.caogao_id=DraftsId.value
    }
    if(editsId.value){
      data.id=editsId.value
    }
    coupePostApi(data).then(res => {
      if(res.code==200){
        redirectTo('/socials/content/content')
      }
      showToast(res.message)
    })
  }

  async function saveHTML(type) {
    // 获取插入的图片列表
    let imgs = await editData.value.getImages()
    console.log(imgs)
    // 判断是否允许提交

    if(type==1||type==2){
      if (!editData.value.textCount && !imgs.length) {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        });
        return false
      }
    }

    // 将所有未上传的本地图片上传到服务器并替换到编辑器
    editData.value.replaceImage(async (img) => {
      if (img.indexOf('http') === 0) {
        return img;
      }
      let data = await uploadApi(img)
      return data;
    }).then(async (res) => {
      let imgss = await editData.value.getImages()
      imgList.value=imgss
      console.log(imgss)
      if (!imgs.length&&(type==1||type==2)) {
        uni.showToast({
          title: '请至少上传一张图片',
          icon: 'none'
        });
      } else {
        console.log('替换完成,最终内容为', JSON.stringify(res));
        if (type == 1) { //预览
          let dataContent={
            content:res.html,
            avatar: userInfo.value.avatar,
            nickname: userInfo.value.name,
            app_user_tag:'doctor',
            create_time:  dayjs().format('MM-DD HH:mm'),
            images: imgList.value[0],
          }
          if(articleTitle.value){
            dataContent.title=articleTitle.value
          }
          if(currentCate.value?.id){
             dataContent.category= currentCate.value?.id
          }
          if(DraftsId.value){
            dataContent.caogao_id=DraftsId.value
          }
          if(editsId.value){
              dataContent.id=editsId.value
          }
          uni.setStorage({
            key:'kepuContent',
            data:JSON.stringify(dataContent)
          })
          // uni.navigateTo({
          //   url: '/socials/preview/preview'
          // });
           redirectTo('/socials/preview/preview')
        } else if(type==2) {
          // 提交
          submit(res.html)
        }else{
          // 草稿
          caogao(res.html)
        }
      }
      // console.log(res)

    });

  }

  async function select(evt) {
    var list = evt.tempFilePaths
    var num = 5 * 1024 * 1024
    for (var i in list) {
      if (list[i].size > num) {
        var a = Number(i) + 1
        uni.showToast({
          title: '第' + a + '张图片上传失败',
          icon: 'none',
          duration: 2000,
        })
        continue
      }
      uni.showLoading({
        title: '上传中...',
      })
      const res = await uploadApi(list[i])
      form.value.imgList.push(res)
      uni.hideLoading()
    }
  }
  // 插入话题示例
  const addLink = () => {
    editData.value.addLink({
      prefix: '#',
      suffix: '#',
      name: '有问题欢迎加入LSJ插件交流群',
    })
  }

  const leftClick = () => {
    showSheet.value = true
  }
  // 获取编辑器内所有的链接
  const getLinks = () => {
    let arr = this.edit.getLink();
  }

  const sheetList = ref([
    {
      name: '保存草稿',
    },
    {
      name: '不保存',
    },
  ])
  const selectClick = async (e) => {
    if (e.name == '保存草稿') {
       saveHTML(3)

    } else {
      flag.value = false
      navigateBack()
    }
  }
  const flag = ref(false)
  watch(isCanSub, (nval) => {
    console.log(nval,"isCanSub.value")
    if (isCanSub.value) {
      flag.value = true
    } else {
      flag.value = false
    }
  })
  onBackPress(({ from }) => {
    console.log(flag.value)
    if (flag.value) {
      showSheet.value = true
      return true
    } else {
      return false
    }
  })
  const savetrendsDrafts = async () => {
    let data = {type:2}

    if (articleTitle.value&&articleTitle.value.length > 0) {
      data.title = articleTitle.value
    }
    if (currentCate.value?.id) {
      data.tag = currentCate.value.id
    }
    if (editData.value.textCount || imgs.length) {
       saveHTML(3)
    }

  }
  const DraftsId=ref(0)
  const caogao=async(html)=>{
    let data = {type:2}
    let imgs = await editData.value.getImages()
    if (articleTitle.value&&articleTitle.value.length > 0) {
      data.title = articleTitle.value
    }
    if (currentCate.value?.id) {
      data.tag = currentCate.value.id
    }
    // if (editData.value.textCount || imgs.length) {

    // }
     data.content = html
     if (imgList.value.length>0) {
        data.link_url=[]
        data.link_url[0]= imgList.value[0]
     }
    if (DraftsId.value) {
       data.id = DraftsId.value
       const res = await CoupeDraftsEditApi(data)
       if (res.code == 200) {
         flag.value = false
         navigateBack()
       }
       showToast(res.message)
    }else{
      const res = await CoupeDraftsAddApi(data)
      if (res.code == 200) {
        flag.value = false
        navigateBack()
      }
      showToast(res.message)
    }


  }
  onUnload(() => {
    // uni.$off('editDrafts')
    uni.removeStorage({
        key:'editDrafts',
        success: function(res){
            console.log('删除成功')
        }
    })
    uni.removeStorage({
        key:'kepuContentPP',
        success: function(res){
            console.log('删除成功')
        }
    })
  })
  const closeSheet=()=>{
    showSheet.value=false
  }
</script>
<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
  .postArtice {
    .postBottom {
      padding: 20rpx;

      // position:fixed;
      // left:0;
      // right:0;
      // bottom:0;
      .postBottomItem {
        width: 340rpx;
        height: 88rpx;
        background: #F5F6F8;
        border-radius: 10rpx;
        font-weight: 500;
        font-size: 26rpx;
        color: #202020;
        border-radius: 10rpx 10rpx 10rpx 10rpx;
        display: flex;
        align-items: center;
        padding: 0 20rpx;
        box-sizing: border-box;

        image {
          width: 30rpx;
          height: 30rpx;
          display: block;
        }

        .arrowRight {
          width: 11rpx;
          height: 19rpx;
          display: block;
          margin-left: 15rpx;
        }

        .title {
          padding-left: 11rpx;
          flex: 1;
        }
      }
    }

    .content {
      padding: 0 25rpx;
    }

    .flex {
      padding: 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1rpx solid #d8d8d8;
      font-weight: bold;
    }

    .btn {
      width: 140rpx;
      line-height: 60rpx;
      margin: 0;
      font-size: 26rpx;
      background-color: #0055ff;
      color: #fff;
    }

    .u-nav-slot {
      width: 211rpx;
      height: 56rpx;
      background: #F5F6F8;
      border-radius: 28rpx;
      font-weight: 400;
      font-size: 30rpx;
      color: #AAAAAA;

      .colorText {
        color: #5C5C5C;
      }

      .colorText1 {
        color: #00C1B9;
      }
    }

    .trendsTitle {
      border-bottom: 1px solid #e1e1e1;
      padding: 20rpx 0;
      display: flex;
      align-items: center;

      textarea {
        font-size: 32rpx;
        color: #202020;
      }

      .icon {
        width: 34rpx;
        height: 34rpx;
        display: block;
        margin-right: 10rpx;
      }

      .inputBox {
        font-size: 24rpx;
        textarea{
          width:690rpx;
        }
      }
    }

    .fixed-bottom {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: #fff;
      // padding: 20rpx 24rpx 15rpx;
      // box-shadow: 0rpx -4rpx 16rpx -4rpx rgba(190, 190, 190, 0.25);
      // background: #fff;
      z-index: 99;

      &.on {
        // bottom: 348px;
        // .edit-btns{
        //   height:50px;
        //   overflow: hidden;
        // }
      }
    }
  }

  .comfirmBtn {
    width: 700rpx;
    text-align: center;
    line-height: 88rpx;
    background: #00C1B9;
    border-radius: 44rpx;
    margin: 20rpx auto;
    font-family: PingFangSC, PingFang SC;
    font-size: 30rpx;
    color: #FFFFFF;
  }

  .popupTitle {
    text-align: center;
    padding: 30rpx 0;
    font-weight: 400;
    font-size: 32rpx;
    color: #202020;
  }

  .yu-datetime-view {
    width: 100%;
    height: 400rpx;
    // overflow: hidden;
    background-color: rgba(255, 255, 255, 1);
    z-index: 666;
  }

  .yu-datetime-view picker-view {
    height: 100%;
  }

  .yu-datetime-view picker-view {
    height: 100%;
  }

  ::v-deep .uni-picker-view-indicator {
    background-color: #F5F6F8;
    z-index: 0;
  }

  .yu-datetime-item {
    text-align: center;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 34rpx;
    color: #202020;
  }
</style>
